// src/stores/auth.js
import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: null,
    username: null, // 新增字段
  }),
  actions: {
    setToken(token) {
      if (typeof token === 'string' && token.trim() !== '') {
        this.token = token;
        localStorage.setItem('token', token);
        console.log('Token 设置成功:', this.token);
      } else {
        console.warn('无效的 token:', token);
      }
    },
    setUsername(username) {
      if (typeof username === 'string' && username.trim() !== '') {
        this.username = username;
        localStorage.setItem('username', username); // 如果需要持久化存储
        console.log('用户名设置成功:', this.username);
      } else {
        console.warn('无效的用户名:', username);
      }
    },
    clearToken() {
      this.token = null;
      localStorage.removeItem('token');
      console.log('Token 清除成功');
    },
    clearUsername() {
      this.username = null;
      localStorage.removeItem('username'); // 如果需要持久化存储
      console.log('用户名清除成功');
    },
    logout() {
      this.clearToken();
      this.clearUsername();
      console.log('用户已登出');
    },
  },
});